<?php

/**
 * vehiculo actions.
 *
 * @package    ACATEC
 * @subpackage vehiculo
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class vehiculoActions extends sfActions
{
  public function executeIndex(sfWebRequest $request)
  {

  	$this->getUser()->setAttribute('current','vehiculo');

  	 // Creamos una vble de usuario que contendrá el id de la empresa
        // Tomamos el nombre de usuario, para obtener a través de la consulta cruzada el id de la empresa
        $user = $this->getContext()->getUser()->getGuardUser();
        $username = $user->getUsername();
    
        //Creamos la consulta para obtener el idempresa a partir del nombre de usuario
        $q = Doctrine_Query::create()
            ->select('empresa_id')
            ->from('CrmContacto c')
            ->where('c.id IN (SELECT u.contacto_id FROM CrmUserContacto u WHERE u.user_id IN 
                             (SELECT s.id FROM SfGuardUser s WHERE s.username= ?))',$username);

        $empresa_id = $q->fetchOne(array(), Doctrine_Core::HYDRATE_ARRAY);
    
        // Y el resultado lo guardamos en la vble de sesión.
        $this->getUser()->setAttribute('empresa_id', $empresa_id['empresa_id']);

  	// Definimos la cultura del usuario por defecto
	//$this->getUser()->setCulture(sfConfig::get('app_culture_default','es'));
	$this->getUser()->setCulture('es');


//    $this->crm_vehiculos = Doctrine_Core::getTable('CrmVehiculo')
//      ->createQuery('a')
//      ->execute();
	// sorting
    if ($request->getParameter('sort') && $this->isValidSortColumn($request->getParameter('sort')))
    {
      $this->setSort(array($request->getParameter('sort'), $request->getParameter('sort_type')));
    }

    // pager
    if ($request->getParameter('page'))
    {
      $this->setPage($request->getParameter('page'));
    }

    $this->pager = $this->getPager();
    $this->sort = $this->getSort();
  }

  public function executeFilter(sfWebRequest $request)
  {
    $this->setPage(1);

    if ($request->hasParameter('_reset'))
    {
      $this->setFilters(array());

      $this->redirect('@crm_vehiculo');
    }

    $this->filters = new CrmVehiculoFormFilter($this->getFilters());

    $this->filters->bind($request->getParameter($this->filters->getName()));
    if ($this->filters->isValid())
    {
      $this->setFilters($this->filters->getValues());

      $this->redirect('@crm_vehiculo');
    }

    $this->pager = $this->getPager();
    $this->sort = $this->getSort();

    $this->setTemplate('index');
  }

  public function executeNew(sfWebRequest $request)
  { 
    // Si viene de contacto porque trae id de contacto  
    if ($request->getParameter('contacto_id')) { 
        $this->forward404Unless($crm_contacto = Doctrine_Core::getTable('CrmContacto')->find(array($request->getParameter('contacto_id'))), sprintf('Object crm_vehiculo does not exist (%s).', $request->getParameter('id')));      
        $crm_vehiculo = new CrmVehiculo();
        $crm_vehiculo->setCrmContacto($crm_contacto);
        $this->cliente=$crm_contacto;
        $this->form = new CrmVehiculoForm($crm_vehiculo);
        $value = $this->cliente->getNombre().' '.$this->cliente->getApellidos();
    } else {  // Si no
        $this->form = new CrmVehiculoForm();
        $value="";
    }
    $this->form->setWidget('cliente_vehiculo',
                        new sfWidgetFormInputText(
                        array(),
                        array(
                                'class'=>'cal',
                                'value'=> $value
                        )));
  }

  public function executeCreate(sfWebRequest $request)
  {
  	$this->forward404Unless($request->isMethod(sfRequest::POST));

    $this->form = new CrmVehiculoForm();

    $this->processForm($request, $this->form);

	$this->setTemplate('new');
  }

  public function executeEdit(sfWebRequest $request)
  {
    $this->forward404Unless($crm_vehiculo = Doctrine_Core::getTable('CrmVehiculo')->find(array($request->getParameter('id'))), sprintf('Object crm_vehiculo does not exist (%s).', $request->getParameter('id')));
    $this->cliente = $crm_vehiculo->getCrmContacto();
    $this->form = new CrmVehiculoForm($crm_vehiculo);
  }
  
  public function executeActualizaClienteId(sfWebRequest $request){
     $cliente_id=$request->getParameter('cliente_id');
     $this->cliente = Doctrine_Core::getTable('CrmContacto')->findOneById($cliente_id);
  }  
  
  public function executeActualizaBusquedaClienteId(sfWebRequest $request){
     $cliente_id=$request->getParameter('cliente_id');
     $this->cliente = Doctrine_Core::getTable('CrmContacto')->findOneById($cliente_id);
  }  
  
  public function executeShow(sfWebRequest $request)
  {
    $this->forward404Unless($crm_vehiculo = Doctrine_Core::getTable('CrmVehiculo')->find(array($request->getParameter('id'))), sprintf('Object crm_vehiculo does not exist (%s).', $request->getParameter('id')));
    $this->vehiculo = $crm_vehiculo;
    $this->cliente = $crm_vehiculo->getCrmContacto();
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($crm_vehiculo = Doctrine_Core::getTable('CrmVehiculo')->find(array($request->getParameter('id'))), sprintf('Object crm_vehiculo does not exist (%s).', $request->getParameter('id')));
    $this->form = new CrmVehiculoForm($crm_vehiculo);

    $this->processForm($request, $this->form);

    $this->setTemplate('edit');
    //$this->setTemplate('new');
  }

   /*
   * Función que indica si un vehiculo tiene documentos asociados 
   */
  protected function tieneDocumentos(CrmVehiculo $vehiculo){
      return (($this->tienePartes($vehiculo)) || ($this->tienePresupuestos($vehiculo)) 
              || ($this->tieneFacturas($vehiculo)));
  }

  protected function tienePartes(CrmVehiculo $vehiculo){
      $idVehiculo = $vehiculo->getId();
      $q = Doctrine_Query::create()
            ->select('id')
            ->from('CrmParte c1')
            ->where('c1.vehiculo_id = ?',$idVehiculo);
      $documentos = $q->fetchOne(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR);
      return ($documentos != null);
  }
  
  protected function tienePresupuestos(CrmVehiculo $vehiculo){
      $idVehiculo = $vehiculo->getId();
      $q = Doctrine_Query::create()
            ->select('id')
            ->from('CrmPresupuesto c1')
            ->where('c1.vehiculo_id = ?',$idVehiculo);
      $documentos = $q->fetchOne(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR);
      return ($documentos != null);
  }
  
  protected function tieneFacturas(CrmVehiculo $vehiculo){
      $idVehiculo = $vehiculo->getId();
      $q = Doctrine_Query::create()
            ->select('id')
            ->from('CrmFactura c1')
            ->where('c1.vehiculo_id = ?',$idVehiculo);
      $documentos = $q->fetchOne(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR);
      return ($documentos != null);
  }
  
  /*
   * Este método elimina un vehiculo, solo si este no tiene documentos asociados (partes, presupuestos o facturas)
   * En caso contrario, lo marca para que no se muestre, pero seguirá en la BD.
   */
  public function executeDelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();
    $this->forward404Unless($crm_vehiculo = Doctrine_Core::getTable('CrmVehiculo')->find(array($request->getParameter('id'))), sprintf('Object crm_vehiculo does not exist (%s).', $request->getParameter('id')));
    //Si no tiene documentos asociados, puedo eliminar el vehiculo
    if (!$this->tieneDocumentos($crm_vehiculo)) {
     	$crm_vehiculo->delete();   
    }
    else{
        $crm_vehiculo->remove_it = TRUE;  
        $crm_vehiculo->save();
    }
    $notice = sfContext::getInstance()->getI18n()->__('Borrado vehículo ').' '.$crm_vehiculo->getMarca().' '.$crm_vehiculo->getModelo().', '.$crm_vehiculo->getMatricula();
    $this->getUser()->setFlash('notice', $notice);

    $this->redirect('vehiculo/index');
  }

  public function executeBatch(sfWebRequest $request)
  {
    $request->checkCSRFProtection();

	if (!$action = $request->getParameter('batch_action'))
    {
      $this->getUser()->setFlash('error', sfContext::getInstance()->getI18n()->__('You must select an action to execute on the selected items.'));

      $this->redirect('@crm_vehiculo');
    }

    if (!$ids = $request->getParameter('ids'))
    {
	  if ($action == 'batchPrint')  // Le hemos dado a imprimir pero sin seleccionar nada. IMPRIMIR TODO
      {
    		if (!method_exists($this, $method = 'execute'.ucfirst($action)))
    		{
      			throw new InvalidArgumentException(sprintf('You must create a "%s" method for action "%s"', $method, $action));
    		}
    		// execute batch executeBachPrint sin ids
      		$this->$method($request);
      }
      $this->getUser()->setFlash('error',sfContext::getInstance()->getI18n()->__('You must at least select one item.'));

      $this->redirect('@crm_vehiculo');
    }

    if (!method_exists($this, $method = 'execute'.ucfirst($action)))
    {
      throw new InvalidArgumentException(sprintf('You must create a "%s" method for action "%s"', $method, $action));
    }


    $validator = new sfValidatorDoctrineChoice(array('multiple' => true, 'model' => 'CrmVehiculo'));
    try
    {
      // validate ids
      $ids = $validator->clean($ids);

      // execute batch
      $this->$method($request);
    }
    catch (sfValidatorError $e)
    {
      $this->getUser()->setFlash('error',sfContext::getInstance()->getI18n()->__('A problem occurs when deleting the selected items as some items do not exist anymore.'));
    }

    $this->redirect('@crm_vehiculo');
  }
  
  
  public function executeImprimir(sfWebRequest $request)
  {
  	// Recogemos los datos del vehiculo
  	$this->forward404Unless($crm_vehiculo = Doctrine_Core::getTable('CrmVehiculo')->find(array($request->getParameter('id'))), sprintf('Object crm_vehiculo does not exist (%s).', $request->getParameter('id')));
  	$vehiculo = $crm_vehiculo;
  	$cliente = $crm_vehiculo->getCrmContacto();
  	
  	//Cargamos los datos del pdf
  	$config = sfTCPDFPluginConfigHandler::loadConfig();
  	// pdf object
  	$pdf = new sfTCPDF();
  	
  	// Variables para generar el documento pdf
  	$titulo = sfContext::getInstance()->getI18n()->__('Datos del Vehiculo'); 
  	$nombre= $vehiculo->getMarca().' '.$vehiculo->getModelo().' '.$vehiculo->getMatricula();
  	$hoy = $this->getUser()->getAttribute('hoy','Lunes');
  	
  	$saltoEncabezado = PDF_HEADER_STRING; 
  	$nombre=strtoupper($nombre);
  	// set document information
  	$pdf->SetCreator(PDF_CREATOR);
  	$pdf->SetAuthor(PDF_AUTHOR);
  	$pdf->SetTitle($titulo);
  	$pdf->SetSubject($nombre);
  	$pdf->SetKeywords('acalio, innova, acatec, crm, desarrollo');
  	
  	
  	// set default header data
  	//$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 001', PDF_HEADER_STRING);
  	$pdf->SetHeaderData('../../../../../web/'.sfConfig::get('pdf_imagenlogo'), PDF_HEADER_LOGO_WIDTH, 
  	         $titulo, $nombre.$saltoEncabezado.$hoy);
  	
  	// set header and footer fonts
  	$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
  	$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
  	
  	// set default monospaced font
  	$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
  	
  	//set margins
  	$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
  	$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
  	$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
  	
  	//set auto page breaks
  	$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
  	
  	//set image scale factor
  	$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  	
  	// ---------------------------------------------------------
  	
  	// set default font subsetting mode
  	$pdf->setFontSubsetting(true);
  	
  	// Set font
  	// dejavusans is a UTF-8 Unicode font, if you only need to
  	// print standard ASCII chars, you can use core fonts like
  	// helvetica or times to reduce file size.
  	$pdf->SetFont('dejavusans', '', 14, '', true);
    
  	// Add a page
  	// This method has several options, check the source code documentation for more information.
  	$pdf->AddPage();
  	
  	// Set some content to print
  	$html = $this->imprimeVehiculo($vehiculo, $cliente);
	
  	// Print text using writeHTMLCell()
  	$pdf->writeHTMLCell($w=0, $h=0, $x='', $y='', $html, $border=0, $ln=1, $fill=0, $reseth=true, $align='', $autopadding=true);
  	
  	// ---------------------------------------------------------
  	
  	// Close and output PDF document
  	// This method has several options, check the source code documentation for more information.
  	$pdf->Output($nombre.'.pdf', 'I');
  	// Stop symfony process
  	throw new sfStopException();
  	
  }
  

  protected function imprimeVehiculo(CrmVehiculo $vehiculo, CrmContacto $cliente){
  	sfContext::getInstance()->getConfiguration()->loadHelpers('Date');
  	$html= '<div>'.
  	'<h2> Datos del cliente </h2>'.
  	'<span style="font-weight: bold;">Nombre: </span>'.
  	'<span>'.$cliente->getNombre().' '.$cliente->getApellidos().'</span><br />'.
  	'<span style="font-weight: bold;">DNI: </span>'.
  	'<span>'.$cliente->getDni().'</span><br />'.
  	'<span style="font-weight: bold;">Dirección: </span>'.
  	'<span>'.$cliente->getDomicilio().'</span><br />'.
  	'<span style="font-weight: bold;">Población: </span>'.
  	'<span>'.$cliente->getPoblacion().'</span><br />';
                
        //Imprimo la lista de telefonos
        $numtel = 1;
        foreach ($cliente->getCrmContactoTelefono() as $telefono){        
            $html= $html.'<span style="font-weight: bold;">Telefono '.$numtel.': </span>'.
            '<span>'.$telefono->getTelefono().' - '. $telefono->getTipo().'</span><br />';            
            $numtel++;
        }        
        
        $numemail = 1;
        //Imprimo la lista de emails
        foreach ($cliente->getCrmContactoEmail() as $email){        
            $html= $html.'<span style="font-weight: bold;">Email '.$numemail.': </span>'.
            '<span>'.$email->getEmail().' - '. $email->getTipo().'</span><br />';            
            $numemail++;
        }        
        
        $html= $html.                
  	'<span style="font-weight: bold;">Descripción: </span>'.
  	'<span>'.$cliente->getDescripcion().'</span><br />'.
  	'</div>'.
  	'<div>'.
  	'<h2> Datos del Vehículo </h2>'.
  	'<span style="font-weight: bold;">Vehículo: </span>'.
  	'<span>'.$vehiculo->getMarca().' '.$vehiculo->getModelo().'</span><br />'.
  	'<span style="font-weight: bold;">Matricula: </span>'.
  	'<span>'.$vehiculo->getMatricula().'</span><br />'.
  	'<span style="font-weight: bold;">Motor: </span>'.
  	'<span>'.$vehiculo->getTipoMotor().'</span><br />'.
  	'<span style="font-weight: bold;">Año: </span>'.
  	'<span>'.$vehiculo->getAnyo().'</span><br />'.
  	'<span style="font-weight: bold;">Kms: </span>'.
  	'<span>'.$vehiculo->getKms().'</span><br />'.
  	'<span style="font-weight: bold;">Seguro: </span>'.
  	'<span>'.$vehiculo->getSeguro().'</span><br />'.
  	'<span style="font-weight: bold;">Fecha ITV: </span>'.
  	'<span>'.format_date($vehiculo->getFechaItv(), "d").'</span><br />'.
  	'<span style="font-weight: bold;">Nº Chasis: </span>'.
  	'<span>'.$vehiculo->getNumeroChasis().'</span><br />'.
  	'<span style="font-weight: bold;">Observaciones: </span>'.
  	'<span>'.$vehiculo->getObservaciones().'</span><br />'.
  	'</div>';
  	return $html;
  }
  
  protected function imprimeListaVehiculos(CrmVehiculo $vehiculo, CrmContacto $cliente){
  	$html= 
      '<td align="center" valign="middle">'.$vehiculo->getMarca().' '.$vehiculo->getModelo().'</td>
      <td align="center" valign="middle">'.$vehiculo->getMatricula().'</td>
      <td align="center" valign="middle">'.$vehiculo->getTipoMotor().'</td>
      <td align="center" valign="middle">'.$vehiculo->getSeguro().'</td>
      <td align="center" valign="middle">'.$vehiculo->getFechaItv().'</td>
      <td align="center" valign="middle">'.$vehiculo->getNumeroChasis().'</td>
      <td align="center" valign="middle">'.$cliente->getNombre().' '.$cliente->getApellidos().'</td>
      <td align="center" valign="middle">'.$cliente->getDni().'</td>
      <td align="center" valign="middle">'.$cliente->getPoblacion().'</td>
      <td align="center" valign="middle">';  
        foreach ($cliente->getCrmContactoTelefono() as $telefono) {
        $html= $html.$telefono->getTelefono().'  ';
      } 
      $html=$html.'</td>';          
    return $html;
  }
  protected function executeBatchDelete(sfWebRequest $request)
  {
    $ids = $request->getParameter('ids');

    $records = Doctrine_Query::create()
      ->from('CrmVehiculo')
      ->whereIn('id', $ids)
      ->execute();

    foreach ($records as $crm_vehiculo)
    {
        //Si no tiene documentos asociados, puedo eliminar el vehiculo
        if (!$this->tieneDocumentos($crm_vehiculo)) {
            $crm_vehiculo->delete();   
        }
        else{
            $crm_vehiculo->remove_it = TRUE;  
            $crm_vehiculo->save();
        }
    }

    $this->getUser()->setFlash('notice', sfContext::getInstance()->getI18n()->__('The selected items have been deleted successfully.'));
    $this->redirect('@crm_vehiculo');
  }

  protected function executeBatchPrint(sfWebRequest $request)
  {

	if (!$ids = $request->getParameter('ids')){  //imprimir sin ids imprime todo
		$records = Doctrine_Query::create()
      ->from('CrmVehiculo')
      ->execute();
	} else {   // imprime solo los ids selecionados
		$records = Doctrine_Query::create()
      ->from('CrmVehiculo')
      ->whereIn('id', $ids)
      ->execute();
	}

		 
	//Cargamos los datos del pdf
	$config = sfTCPDFPluginConfigHandler::loadConfig();
	// pdf object
	$pdf = new sfTCPDF();
	 
	// Variables para generar el documento pdf
	$titulo = sfContext::getInstance()->getI18n()->__('Lista de Vehiculos');
	$hoy = $this->getUser()->getAttribute('hoy','Lunes');
	 
	$saltoEncabezado = PDF_HEADER_STRING;
	// set document information
	$pdf->SetCreator(PDF_CREATOR);
	$pdf->SetAuthor(PDF_AUTHOR);
	$pdf->SetTitle($titulo);
	$pdf->SetSubject($titulo);
	$pdf->SetKeywords('acalio, innova, acatec, crm, desarrollo');
	 
	 
	// set default header data
	$pdf->SetHeaderData('../../../../../web/'.sfConfig::get('pdf_imagenlogo'), PDF_HEADER_LOGO_WIDTH,
	$titulo, $saltoEncabezado.$hoy);
	 
	// set header and footer fonts
	$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
	$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
	 
	// set default monospaced font
	$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
	 
	//set margins
	$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
	$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
	$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
	 
	//set auto page breaks
	$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
	 
	//set image scale factor
	$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
	 
	// ---------------------------------------------------------
	 
	// set default font subsetting mode
	$pdf->setFontSubsetting(true);
	 
	// Set font
	// dejavusans is a UTF-8 Unicode font, if you only need to
	// print standard ASCII chars, you can use core fonts like
	// helvetica or times to reduce file size.
	$pdf->SetFont('dejavusans', '', 8, '', true);
	 
		 
	// Add a page
	// This method has several options, check the source code documentation for more information.
	$pdf->AddPage();
	 
	// Set some content to print
	$html = 
	'<table border="1">
	   <thead>
	      <tr style="background-color:#0000FF;color:#FFFF00;">
            <td colspan="6" align="center"><b>Vehiculo</b></td>
            <td colspan="4" align="center"><b>Cliente</b></td>
          </tr>
	      <tr style="background-color:#FFFF00;color:#0000FF;">
            <td align="center"><b>Vehiculo</b></td>
            <td align="center"><b>Matricula</b></td>
            <td align="center"><b>Motor</b></td>
            <td align="center"><b>Seguro</b></td>
            <td align="center"><b>ITV</b></td>
            <td align="center"><b>Nº Chasis</b></td>
            <td align="center"><b>Nombre</b></td>
            <td align="center"><b>DNI</b></td>
            <td align="center"><b>Población</b></td>
            <td align="center"><b>Teléfono</b></td>
          </tr>
        </thead>';
 	
	$ind=0; 
    foreach ($records as $record)
    {   
    	$ind=$ind+1;
    	if (($ind % 2) == 0) {
    		$html= $html.'<tr style="background-color:#FFCCCC;">';
    	}else{
    	   $html= $html.'<tr>';
    	}
    	$cliente = $record->getCrmContacto();
    	$html=$html.$this->imprimeListaVehiculos($record,$cliente);
    	$html= $html.'</tr>';
    }
    $tbl=$html.'</table>';
    
    
    // Print text using writeHTMLCell()
    $pdf->writeHTML($tbl, true, false, false, false, '');
    
    // ---------------------------------------------------------
	 
	// Close and output PDF document
	// This method has several options, check the source code documentation for more information.
	$pdf->Output($titulo.'.pdf', 'I');
	// Stop symfony process
	throw new sfStopException();
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
        $crm_vehiculo = $form->save();
        // $this->redirect('vehiculo/edit?id='.$crm_vehiculo->getId());
        $this->getUser()->setFlash('notice', sfContext::getInstance()->getI18n()->__('El vehículo '.$this->form->getValue('marca').' '.
    												    $this->form->getValue('modelo').', '.
    												   'matricula '.$this->form->getValue('matricula').
    												   ' ha sido guardado'));
        // Hacer solo si viene de nuevo "Guardar y dar de alta orden de trabajo"
        if ($request->getPostParameter('AddParte') != 0) {
              $this->redirect('parte/new?contacto_id='.$crm_vehiculo->getClienteId().'&vehiculo_id='.$crm_vehiculo->getId());
        }     
        $this->redirect('vehiculo/index');
    }
  }

  protected function getFilters()
  {
    return $this->getUser()->getAttribute('vehiculo.filters');
  }

  protected function setFilters(array $filters)
  {
    return $this->getUser()->setAttribute('vehiculo.filters', $filters);
  }

  protected function getPager()
  {
    //Obtengo el número de contactos a mostrar de la base de datos (tabla CrmConfiguracion)
    $campo = "numRegistros";
    $q = Doctrine_Query::create()
    ->select('valor')
    ->from('CrmConfiguracion c1')
    ->where('c1.campo = ?',$campo);
    $numelementos = $q->fetchOne(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR);
      
    $pager = new sfDoctrinePager('CrmVehiculo', $numelementos);  
    //$pager = new sfDoctrinePager('CrmVehiculo', sfConfig::get('app_list_max_vehiculos'));
    $pager->setQuery($this->buildQuery());
    $pager->setPage($this->getPage());
    $pager->init();

    return $pager;
  }

  protected function setPage($page)
  {
    $this->getUser()->setAttribute('vehiculo.page', $page);
  }

  protected function getPage()
  {
    return $this->getUser()->getAttribute('vehiculo.page', 1);
  }

  protected function buildQuery()
  {
    $tableMethod = 'CrmVehiculo';
    $filterValues = $this->getFilters();
    $this->valores = $filterValues;
    $borrado = 1;
    //create a default query donde no muestro los marcados para borrar
    $query = Doctrine_Core::getTable('CrmVehiculo')->createQuery('p')->where('p.remove_it <> ?',$borrado)
            ->orWhere('p.remove_it IS NULL');

    if (null === $this->filtro)
    {
      $this->filtro = new CrmVehiculoFormFilter($filterValues);
    }

    //if the form have been submited
    if($filterValues){
      //bind the values
      $this->filtro->bind($filterValues);
      //if valid, specialise the request using the form
      if($this->filtro->isValid())
         $query = $this->filtro->getQuery();
         //Añado condiciones para que en las búsquedas no se muestren los elementos marcados para borrado
         $query->andWhere($query->getRootAlias().'.remove_it IS NULL OR '.$query->getRootAlias().'.remove_it <> ?',$borrado);
    }

    $this->addSortQuery($query);

    $event = $this->dispatcher->filter(new sfEvent($this, 'crm.build_query'), $query);
    $query = $event->getReturnValue();

    return $query;
  }

  protected function addSortQuery($query)
  {
    if (array(null, null) == ($sort = $this->getSort()))
    {
      return;
    }

    if (!in_array(strtolower($sort[1]), array('asc', 'desc')))
    {
      $sort[1] = 'asc';
    }

    $query->addOrderBy($sort[0] . ' ' . $sort[1]);
  }

  protected function getSort()
  {
    if (null !== $sort = $this->getUser()->getAttribute('vehiculo.sort'))
    {
      return $sort;
    }

    $this->setSort(array('id',sfConfig::get('app_sort_default','asc')));

    return $this->getUser()->getAttribute('vehiculo.sort');
  }

  protected function setSort(array $sort)
  {
    if (null !== $sort[0] && null === $sort[1])
    {
      $sort[1] = 'asc';
    }

    $this->getUser()->setAttribute('vehiculo.sort', $sort);
  }

  protected function isValidSortColumn($column)
  {
    return Doctrine_Core::getTable('CrmVehiculo')->hasColumn($column);
  }
  
  
}